﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Compilation;
using System.Xml;
using visinia.SmartEngine.Installer;

namespace visinia.SmartEngine.SiteMap
{
    public class SiteMapController
    {
        internal static void GenerateSiteMap(HttpContext context)
        {
            using (XmlWriter writer = XmlWriter.Create(context.Response.OutputStream))
            {
                writer.WriteStartElement("urlset", "http://www.google.com/schemas/sitemap/0.84");
                GetPluginSiteMapData().ForEach(delegate(SiteMapInfo sitemapInfo)
                {
                    AddNode(writer, sitemapInfo.Url, sitemapInfo.LastModified, sitemapInfo.ChangeFrequency);
                });
                writer.WriteEndElement();
            }
            context.Response.ContentType = "text/xml";
        }

        public static List<SiteMapInfo> GetPluginSiteMapData()
        {
            List<SiteMapInfo> list = new List<SiteMapInfo>();
            PluginController.GetInstalledPlugins().ForEach(delegate(Plugin plugin)
            {
                if (!string.IsNullOrEmpty(plugin.SiteMapController))
                {                   
                    Type type = BuildManager.GetType(plugin.SiteMapController, false, true);
                    BaseSiteMap baseSitemap = (BaseSiteMap)Activator.CreateInstance(type);
                    list.AddRange(baseSitemap.GenerateSiteMap());
                }
            });
            return list;
        }

        /// <summary>
        /// Adds a new node
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="loc">The Url to be added</param>
        /// <param name="lastmod">The last modified date</param>
        /// <param name="changefreq">The change frequency</param>
        private static void AddNode(XmlWriter writer, string loc, DateTime lastmod, SiteMapInfo.ChangeFreq changefreq)
        {            
            writer.WriteStartElement("url");
            writer.WriteElementString("loc", loc);
            writer.WriteElementString("lastmod", lastmod.ToString("yyyy-MM-dd"));
            writer.WriteElementString("changefreq", changefreq.ToString());
            writer.WriteEndElement();
        }
    }
}
